// 编辑器视图组件
import React, { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { TabBar } from '../components/TabBar';
import { TabEditor } from '../components/TabEditor';
import { PerformanceMonitor } from '../components/PerformanceMonitor';
import { FileItem } from '../types/filesystem';
import { useFileSystemStore } from '../stores/fileSystemStore';
import { useTabStore, TabStatus } from '../stores/tabStore';
import { useKeyboardShortcuts } from '../hooks/useKeyboardShortcuts';
import { useAutoSave } from '../hooks/useAutoSave';
import { getLazyLoadManager } from '../services/lazyLoadManager';

interface EditorViewProps {
  className?: string;
}

export const EditorView: React.FC<EditorViewProps> = ({ className }) => {
  const [showPerformanceMonitor, setShowPerformanceMonitor] = useState(false);
  
  const { loadDirectory } = useFileSystemStore();
  const { openTab, saveTab, saveAllTabs, updateTabStatus, tabs, tabOrder, activeTabId } = useTabStore();

  // 懒加载管理器
  const lazyLoadManager = getLazyLoadManager({
    enabled: true,
    preloadDistance: 2,
    maxPreloadedTabs: 5,
    contentThreshold: 50, // 50KB
  });

  // 处理文件打开
  const handleFileOpen = async (file: FileItem) => {
    console.log('Opening file:', file.path);

    try {
      // 读取文件内容
      const response = await invoke('read_file', { path: file.path }) as any;
      const content = response.success ? response.data : '';

      // 在新标签页中打开文件
      await openTab(file.path, content);
    } catch (err) {
      console.error('Failed to open file:', err);
    }
  };

  // 处理新建标签页
  const handleNewTab = async () => {
    await openTab('Untitled', '', { isTemporary: true });
  };

  // 处理编辑器内容变化
  const handleContentChange = (tabId: string, _content: string) => {
    // 标记为已修改状态
    updateTabStatus(tabId, TabStatus.Modified);
  };

  // 处理光标位置变化
  const handleCursorPositionChange = (tabId: string, line: number, column: number) => {
    console.log(`Cursor moved in ${tabId}: ${line}:${column}`);
  };

  // 处理选择变化
  const handleSelectionChange = (tabId: string, selection: any) => {
    console.log(`Selection changed in ${tabId}:`, selection);
  };

  // 键盘快捷键支持
  useKeyboardShortcuts({
    onNewTab: handleNewTab,
    onSaveTab: (tabId) => {
      saveTab(tabId);
    },
    onSaveAllTabs: () => {
      saveAllTabs();
    },
  });

  // 自动保存功能
  useAutoSave({
    config: {
      enabled: true,
      interval: 30000, // 30秒自动保存
      saveOnFocusLoss: true,
      saveOnTabSwitch: true,
      sessionRecovery: true,
    },
    onSave: (tabId, success) => {
      if (success) {
        console.log(`Auto-saved tab: ${tabId}`);
      } else {
        console.error(`Failed to auto-save tab: ${tabId}`);
      }
    },
    onSessionRecovered: (tabCount) => {
      console.log(`Session recovered with ${tabCount} tabs`);
    },
  });

  // 监听标签页变化，更新懒加载管理器
  useEffect(() => {
    lazyLoadManager.updateTabOrder(tabOrder, activeTabId);

    // 注册新标签页
    Array.from(tabs.values()).forEach((tab, index) => {
      if (lazyLoadManager.getLoadState(tab.id) === undefined) {
        lazyLoadManager.registerTab(tab, index);
      }
    });
  }, [tabs, tabOrder, activeTabId, lazyLoadManager]);

  // 处理性能问题
  const handlePerformanceIssue = (metrics: any) => {
    console.warn('Performance issue detected:', metrics);

    // 如果内存使用过高，可以触发一些优化措施
    if (metrics.health.status === 'critical') {
      // 例如：强制垃圾回收、关闭非活动标签页等
      console.log('Triggering performance optimizations...');
    }
  };

  return (
    <div className={`flex-1 flex flex-col ${className || ''}`}>
      {/* 标签页栏 */}
      <div className="flex items-center border-b border-gray-200 dark:border-gray-700">
        <TabBar
          onNewTab={handleNewTab}
          className="flex-1"
        />

        {/* 性能监控切换按钮 */}
        <button
          className="px-3 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700 border-l border-gray-200 dark:border-gray-700"
          onClick={() => setShowPerformanceMonitor(!showPerformanceMonitor)}
          title={showPerformanceMonitor ? '隐藏性能监控' : '显示性能监控'}
        >
          📊
        </button>
      </div>

      {/* 编辑器内容区域 */}
      <div className="flex-1 bg-gray-100 dark:bg-gray-700 flex flex-col">
        <TabEditor
          className="flex-1"
          onContentChange={handleContentChange}
          onCursorPositionChange={handleCursorPositionChange}
          onSelectionChange={handleSelectionChange}
        />

        {/* 性能监控器 */}
        {showPerformanceMonitor && (
          <div className="border-t border-gray-200 dark:border-gray-700">
            <PerformanceMonitor
              className="p-2"
              showDetails={true}
              onPerformanceIssue={handlePerformanceIssue}
            />
          </div>
        )}
      </div>
    </div>
  );
};
